<template>
  <div>
  <el-table :data="paginatedData" :show-header="true" style="width: 100%">
    <el-table-column prop="pos" label='行政区' ></el-table-column>
    <el-table-column prop="types" label='传感器' ></el-table-column>
    <el-table-column prop="productid" label='产品号' ></el-table-column>
    <el-table-column prop="time" label='采集时间'  :formatter="formatTime" align="center"></el-table-column>
    <el-table-column label="缩略图">
      <template slot-scope="scope">
        <!-- 根据 productid 构造图片 src -->
        <img :src="'https://gaofeitupian.gzrhcloud.cn/icons/' + scope.row.productid + '.jpg'" align="center" style="width: 50px; height: 50px;" @click="showEnlargeImage(scope.row)">
      </template>
    </el-table-column>
    <el-table-column align="right">
    <template slot-scope="scope">
        <el-switch
        v-if="scope.row.id !== null" 
        v-model="scope.row.switchValue" 
        active-color="#1f2024" 
        inactive-color="#f1e8e8" 
        @change="handleSwitchChange(scope.row)"></el-switch>
    </template>
    </el-table-column>
  </el-table>
  <div class="pagination">
  <el-pagination
    @current-change="handlePageChange"
    :current-page="currentPage"
    :page-sizes="[10, 20, 30, 40]"
    :page-size="pageSize"
    layout="total, sizes, prev, pager, next, jumper"
    :total="tableData.length"
  ></el-pagination>
  </div>
  <el-button type="primary" @click="submitJson" class="query-button">提交</el-button>
  <!-- Dialog 组件 -->
  <el-dialog
    title="审批结果"
    :visible.sync="dialogVisible"
    width="60%">
    <el-table :data="dialogTableData" style="width: 100%">
      <el-table-column prop="gid" label="gid" width="auto"></el-table-column>
      <el-table-column prop="productId" label="产品号"></el-table-column>
      <el-table-column prop="acquisitionTime" label="采集时间" :formatter="formatTime"></el-table-column>
      <el-table-column prop="pos" label="行政区"></el-table-column>
      <el-table-column prop="types" label="传感器"></el-table-column>
      <el-table-column label="审核状态">
        <template slot-scope="scope">
          {{ scope.row.status === '01' ? '未通过' : scope.row.status === '02' ? '已通过' : '未知' }}
        </template>
      </el-table-column>
      <el-table-column  label="下载链接">
        <template slot-scope="scope">
          <!-- 使用 v-if 控制下载链接的显示 -->
          <a v-if="scope.row.status === '02'" :href="'http://47.97.196.173:3000/rawfiles/' + scope.row.productId + '.tar.gz'" target="_blank">下载</a>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>
    <!-- 放大图片的弹出框 -->
    <el-dialog title="放大图" :visible.sync="showEnlargeImageDialog">
      <img :src="enlargedImageUrl" style="max-width: 100%; max-height: 100%;" />
    </el-dialog>
  </div>
</template>

<script>
import { EventBus } from '../../EventBus';
import axios from 'axios';
export default {
data() {
  return {
    tableData:[{
      gid:null,
      productid:'',
      time:'',
      url:'',
      types:'',
      pos:'',
      switchValue: false,
    }],
      currentPage: 1,
      pageSize: 10,
      selectedList: [], // 存储选中的 gid 和 productid
      dialogVisible: false, // 控制 Dialog 显示状态
      dialogTableData: [], // 存储 Dialog 中的表格数据
            showEnlargeImageDialog: false, // 控制放大图片弹出框的显示状态
      enlargedImageUrl: '' // 放大后图片的 URL

  }
},
created() {
    // 监听来自 EventBus 的事件，更新数据
    EventBus.$on('update-table-data', (data) => {
        // 清空 selectedList
      this.selectedList = [];
      // 设置 switchValue 为 true 并发送事件
      this.tableData = data.map(item => {
        const newItem = {
          ...item,
          switchValue: true
        };
        // 发送事件通知开关状态变化
        EventBus.$emit('switch-change', { gid: newItem.gid, productid: newItem.productid, switchValue: newItem.switchValue });
        // 添加到选中列表
        this.addToSelectedList(newItem.gid, newItem.productid, newItem.time, newItem.pos, newItem.types);
        return newItem;
      });
    });
  },
methods: {
  handleSwitchChange(row) {
    // 触发事件，传递 ID 和 layers
    // console.log(row.switchValue)
    if (row.switchValue) {
        // 添加到列表
        this.addToSelectedList(row.gid, row.productid, row.time, row.pos, row.types);
      } else {
        // 从列表中移除
        this.removeFromSelectedList(row.gid, row.productid, row.time, row.pos, row.types);
      }
      EventBus.$emit('switch-change', { gid: row.gid, productid: row.productid, switchValue: row.switchValue });
    // 如果 switchValue 变为 false，触发 queryshow-switch-change 事件
    if (!row.switchValue) {
      // console.log(row.switchValue)
      EventBus.$emit('queryshow-switch-change', { gid: row.gid, switchValue: false });
      }
    },
  addToSelectedList(gid, productid, time, pos, types) {
      const existingItem = this.selectedList.find(item => item.gid === gid);
      if (!existingItem) {
        this.selectedList.push({ gid, productid, time, pos, types });
      }
    },
  removeFromSelectedList(gid, productid, time, pos, types) {
      const index = this.selectedList.findIndex(item => item.gid === gid 
                                                && item.productid === productid 
                                                && item.time === time 
                                                && item.pos === pos 
                                                && item.types === types);
      if (index !== -1) {
        this.selectedList.splice(index, 1);
      }
    },
    formatTime(row,column){
    let data = row[column.property]
    let dtime = new Date(data)
    const year = dtime.getFullYear()
    let month = dtime.getMonth() + 1
    if (month < 10) {
        month = '0' + month
    }
    let day = dtime.getDate()
    if (day < 10) {
        day = '0' + day
    }
    return year+ '-' + month+ '-' + day + ' '
    },
    handlePageChange(newPage) {
      this.currentPage = newPage;
    },
    submitJson() {
      const jsonData = JSON.stringify(this.selectedList);
      // console.log(jsonData);
      // axios.post('http://127.0.0.1:81/submit', jsonData, {
      //   headers: {
      //     'Content-Type': 'application/json'
      //   }
      // })
      // .then(response => {
      //   console.log(response.data);
      //   // 处理成功响应
      // })
      // .catch(error => {
      //   console.error(error);
      //   // 处理错误响应
      // });
     // 向父页面发送消息
    const parent = window.parent;
    if (parent) {
      parent.postMessage({
        type: 'showFormDialog',
        data: jsonData // 直接发送 jsonData
        }, '*');
      };
    // 新增代码部分：请求父页面数据并显示对话框
    parent.postMessage({ type: 'requestTableData' }, '*');
    // 监听父页面返回的数据
    window.addEventListener('message', (event) => {
      if (event.data.type === 'responseTableData') {
        const responseData = event.data.responseData;
        const appData = responseData.appData;
        const status = responseData.status;
      // 将父页面传来的 appData 中的数据与 dialogTableData 合并
      this.dialogTableData = appData.map(item => {
        return {
          gid: item.gid,
          productId: item.productId,
          acquisitionTime: item.acquisitionTime,
          pos: item.pos,
          types: item.types,
          status: status
        };
      });
        // console.log(this.dialogTableData);
        // 显示对话框
        this.dialogVisible = true;
        }
      }, { once: true });
    },
    showEnlargeImage(row) {
      // 构造放大后图片的 URL
      this.enlargedImageUrl = 'https://gaofeitupian.gzrhcloud.cn/icons/' + row.productid + '.jpg';
      // 显示放大图片的弹出框
      this.showEnlargeImageDialog = true;
    },
  },
  
computed: {
  paginatedData() {
    const startIndex = (this.currentPage - 1) * this.pageSize;
    const endIndex = startIndex + this.pageSize;
    return this.tableData.slice(startIndex, endIndex);
  },
},
};
</script>

<style scoped>
.pagination{
  max-width: 100%;
  overflow-x: auto;
  display: flex;
}
.query-button {
  position: relative;
  margin-top: 15px;
  margin-left: 70%; /* 调整上方边距，根据需要调整数值 */
}
</style>
